import os
import sys

from PyQt6 import uic
from PyQt6.QtGui import QIcon
from PyQt6.QtWidgets import QWidget, QFileDialog, QMessageBox
import json

from utils.error import getError
from utils.index import resource_path


class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.old_directory = None
        self.ui = uic.loadUi(resource_path("static/ui/setting.ui"), self)  # 加载 UI 文件
        self.init()  # 初始化

    # ========================================================
    # 初始化
    # ========================================================

    def init(self):
        # 初始化样式
        self.init_style()
        # 初始化内容
        self.init_content()
        # 初始化事件
        self.init_event()

    # 初始化样式
    def init_style(self):
        self.ui.setWindowTitle("SeismicPlot-设置")
        self.ui.setWindowIcon(QIcon(resource_path('static/image/favicon.ico')))

    # 初始化内容
    def init_content(self):
        with open(resource_path("static/json/setting.json"), 'r', encoding='utf-8') as file:
            data = json.load(file)
        arr = data["history_path"].split("/")
        arr.pop()
        directory = "/".join(arr)
        self.old_directory = directory
        self.ui.lineEdit.setText(directory)

    # 初始化事件
    def init_event(self):
        self.ui.toolButton.clicked.connect(self.select_directory)
        # 连接按钮的点击事件
        self.ui.buttonBox.accepted.connect(self.accept_action)
        self.ui.buttonBox.rejected.connect(self.reject_action)

    # ========================================================
    # 工具函数
    # ========================================================

    # 目录选择框
    def select_directory(self):
        directory = QFileDialog.getExistingDirectory(self, '选择目录', '', QFileDialog.Option.ShowDirsOnly)
        if directory:
            self.ui.lineEdit.setText(directory)

    # Ok
    def accept_action(self):
        directory = self.ui.lineEdit.text()
        file_path = self.ui.lineEdit.text() + "/historyList.json"
        if directory == "None":
            application_path = ''
            # 获取可执行文件所在的目录
            if getattr(sys, 'frozen', False):
                # 如果是打包后的可执行文件
                application_path = os.path.dirname(sys.executable)
            else:
                # 如果是脚本运行
                # application_path = os.path.dirname(os.path.abspath(__file__))
                application_path = r"D:\myFile\appDev"
            path = os.path.join(application_path, 'historyList.json')
            arr = path.split('\\')
            path = "/".join(arr)
            arr = path.split("/")
            arr.pop()
            dir = "/".join(arr)
            try:
                if os.path.exists(path):  # 当该路径下存在历史记录文件时
                    result = QMessageBox.question(self, '设置-保存历史记录的目录','应用所在目录已存在保存历史记录的文件，是否“覆盖”该目录下的历史记录文件？',
                                                  QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.No)
                    if result == QMessageBox.StandardButton.Ok:  # 覆盖原来的文件
                        self.update_hisotry_path('update', path)
                        self.ui.lineEdit.setText(dir)  # 更新输入框中的路径
                    elif result == QMessageBox.StandardButton.No:  # 不覆盖，修改设置中的历史记录
                        # 修改setting.json中记录的历史记录文件的路径
                        with open(resource_path("static/json/setting.json"), 'r', encoding='utf-8') as file:
                            data = json.load(file)
                        data["history_path"] = path
                        with open(resource_path("static/json/setting.json"), 'w', encoding='utf-8') as file:
                            json.dump(data, file, indent=4)
                        self.ui.lineEdit.setText(dir)  # 更新输入框中的路径
                        QMessageBox.information(self, '操作成功', '保存历史记录文件的目录修改成功！',
                                                QMessageBox.StandardButton.Ok)
                else:
                    data_list = {
                        "bridge": [],
                        "mul_wave": [],
                        "layered": [],
                        "joint_well": []
                    }
                    # 重新生成历史记录文件
                    with open(path, 'w', encoding='utf-8') as file:
                        json.dump(data_list, file, indent=4)
                    # 修改setting.json中记录的历史记录文件的路径
                    with open(resource_path("static/json/setting.json"), 'r', encoding='utf-8') as file:
                        data = json.load(file)
                    data["history_path"] = path
                    with open(resource_path("static/json/setting.json"), 'w', encoding='utf-8') as file:
                        json.dump(data, file, indent=4)
                    self.ui.lineEdit.setText(dir)  # 更新输入框中的路径
                    QMessageBox.information(self, '操作成功', f'成功将历史记录文件保存到{path}！',
                                            QMessageBox.StandardButton.Ok)
            except:
                err = getError()
                QMessageBox.critical(self, f"{err['type']}", f"{err['msg']}", QMessageBox.StandardButton.Ok)
        elif directory == "":
            result = QMessageBox.question(self, '设置-保存历史记录的目录', '停止使用历史记录？', QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.No)
            if result == QMessageBox.StandardButton.Ok:  # 停止使用历史记录
                # 修改setting.json中记录的历史记录文件的路径
                with open(resource_path("static/json/setting.json"), 'r', encoding='utf-8') as file:
                    data = json.load(file)
                data["history_path"] = ""
                with open(resource_path("static/json/setting.json"), 'w', encoding='utf-8') as file:
                    json.dump(data, file, indent=4)
                QMessageBox.information(self, '操作成功', '成功停用历史记录！', QMessageBox.StandardButton.Ok)
            elif result == QMessageBox.StandardButton.No:  # 取消
                pass
        elif self.old_directory == directory:
            if os.path.exists(file_path):  # 当该路径下存在历史记录文件时
                result = QMessageBox.question(self, '设置-保存历史记录的目录', '该目录已存在保存历史记录的文件，是否“覆盖”该目录下的历史记录文件？',
                                              QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.No)
                if result == QMessageBox.StandardButton.Ok:  # 覆盖原来的文件
                    self.update_hisotry_path()
                elif result == QMessageBox.StandardButton.No:  # 不覆盖
                    pass
            else:  # 该路径下不存在历史记录文件时
                result = QMessageBox.question(self, '设置-保存历史记录的目录',
                                              f'当前目录下不存在历史记录文件，是否将历史记录文件保存到{directory}目录下？',
                                              QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.No)
                if result == QMessageBox.StandardButton.Ok:  # 生成新文件
                    self.update_hisotry_path('new')
                elif result == QMessageBox.StandardButton.No:  # 取消
                    pass
        else:
            if os.path.exists(file_path):
                result = QMessageBox.question(self, '设置-保存历史记录的目录', '该目录已存在保存历史记录的文件，是否“覆盖”该目录下的历史记录文件？',
                                              QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.No)
                if result == QMessageBox.StandardButton.Ok:  # 覆盖原来的文件
                    self.update_hisotry_path()
                elif result == QMessageBox.StandardButton.No:  # 不覆盖原来的文件，但修改文件路径
                    # 修改setting.json中记录的历史记录文件的路径
                    with open(resource_path("static/json/setting.json"), 'r', encoding='utf-8') as file:
                        data = json.load(file)
                    data["history_path"] = file_path
                    with open(resource_path("static/json/setting.json"), 'w', encoding='utf-8') as file:
                        json.dump(data, file, indent=4)
                    QMessageBox.information(self, '操作成功', '保存历史记录文件的目录修改成功！', QMessageBox.StandardButton.Ok)
            else:
                self.update_hisotry_path('new')

    # 更新存放历史记录的路径
    def update_hisotry_path(self, type='update', path=None):
        data_list = {
            "bridge": [],
            "mul_wave": [],
            "layered": [],
            "joint_well": []
        }
        if path is None:
            path = self.ui.lineEdit.text() + "/historyList.json"
        try:
            # 重新生成历史记录文件
            with open(path, 'w', encoding='utf-8') as file:
                json.dump(data_list, file, indent=4)
            # 关闭弹窗
            self.ui.close()
            # 修改setting.json中记录的历史记录文件的路径
            with open(resource_path("static/json/setting.json"), 'r', encoding='utf-8') as file:
                data = json.load(file)
            data["history_path"] = path
            with open(resource_path("static/json/setting.json"), 'w', encoding='utf-8') as file:
                json.dump(data, file, indent=4)
            if type == 'update':  # 判断类型是覆盖还是新建
                QMessageBox.information(self, '操作成功', '成功覆盖原文件！', QMessageBox.StandardButton.Ok)
            else:
                QMessageBox.information(self, '操作成功', '成功生成历史记录文件！', QMessageBox.StandardButton.Ok)
        except:
            err = getError()
            QMessageBox.critical(self, f"{err['type']}", f"{err['msg']}", QMessageBox.StandardButton.Ok)

    # CanCel
    def reject_action(self):
        self.ui.close()
